package saver

import (
	"fmt"
	"github.com/jmoiron/sqlx"
	"my-crawler/concurrence/task/mohurd/query"
	"my-crawler/database/mysql"
	"time"
)

func Saver() chan interface{} {
	//任务开始时先创建这个通道
	//这里不仅可以初始化一些其他事情 例如初始化数据库 减少连接
	out := make(chan interface{}, 1)
	client := mysql.Db
	go func() {
		itemCount := 0
		for {
			item := <-out //接收 engine发过来的item
			itemCount++
			MohurdJoinDetail(client, item)
		}
	}()
	return out
}

func UpdateInMysql(db *sqlx.DB, item interface{}) {
	res := item.(query.Result)
	fmt.Println(res)
	for _, i := range res.Data.List {
		r, err := db.Exec(
			"insert into mohurd(ROW_GU,工程名称, 建设地址, 工程项目编号,施工许可证电子证照编号,项目分类,"+
				"项目属地,建设单位代码,建设单位项目负责人,项目负责人证件号码,计划开工日期,计划竣工日期,合同价格,"+
				"总面积,合计地上面积,合计地下面积,发证机关代码,签发日期,管理属地,建设单位,发证机关,建设规模)"+
				"values(?,?, ?,?, ?,?, ?,?, ?,?, ?,?, ?,?, ?,?, ?,?, ?,?, ?,?)",
			i.ROW_GU, i.PROJNAME, i.PROJLOC, i.PRJNUM, i.CERTNUM, i.PRJTYPENUM, i.RISSUAUTH, i.PROJOWNERCODE, i.OWNERMNGR,
			i.OWNERMNGRCARDNO, i.PSTARTDATE, i.PCOMPDATE, i.CONPRICE, i.TOTALHAREA, i.TOTALAHAREA, i.TOTALUHAREA,
			i.ISSUAUTHCODE, i.ISSUDATE, i.RISSUAUTH, i.PROJOWNER, i.ISSUAUTH, i.PROJSCALE)
		if err != nil {
			fmt.Println("exec failed, ", err)
			return
		}
		_, err = r.LastInsertId()
		if err != nil {
			fmt.Println("exec failed, ", err)
			return
		}
	}

}
func MohurdJoinDetail(db *sqlx.DB, item interface{}) {
	res := item.(query.Detail1Result)

	for _, i := range res.Data.List {
		fmt.Printf("%+v", i)
		seconds := i.CREATETIME
		unix := time.Unix(seconds/1000, 0)
		r, err := db.Exec(
			"insert into mohurd_join_detail(RELATIONGUID,CORPROLENAME,CORPNAME,CORPCODE,PERSONNAME,CREATETIME)"+
				"values(?,?, ?,?, ?,?)",
			res.Data.RELATIONGUID, i.CORPROLENAME, i.CORPNAME, i.CORPCODE, i.PERSONNAME, unix.Format("2006-01-02 15:04:05.999999999"))
		if err != nil {
			fmt.Println("exec failed, ", err)
			return
		}
		_, err = r.LastInsertId()
		if err != nil {
			fmt.Println("exec failed, ", err)
			return
		}
	}

}
